package co.fitstart.admin.web.controller.content;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import co.fitstart.admin.entity.content.ArticleModuleSearch;
import co.fitstart.admin.entity.content.ArticleSearch;
import co.fitstart.admin.service.ArticleService;
import co.fitstart.admin.service.DataService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.entity.content.Article;
import co.fitstart.entity.content.ArticleModule;
import co.fitstart.entity.content.Module;

import com.demo2do.core.persistence.support.Order;
import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;

/**
 * 
 * @author lidan
 *
 */
@Controller
@RequestMapping("/articles")
@MenuSetting("menu-content")
public class ArticleController {
    
    private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
    
    @Autowired
    @Qualifier("articleService")
    private ArticleService articleService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<Module> moduleService;
    
    /**
     * 
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method=RequestMethod.GET)
    @MenuSetting("submenu-article-management")
    public ModelAndView list(Page page,
                             HttpServletRequest request){
        
        ModelAndView modelAndView = new ModelAndView("content/article/article-list");
            
        List<Article> articles = articleService.listByPage(Article.class,
                                                           new Order("createTime", "DESC"),
                                                           page);
        
        modelAndView.addObject("articles", articles);
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "list");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param moduleId
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method=RequestMethod.GET, params = "moduleId")
    @MenuSetting("submenu-article-management")
    public ModelAndView list(@RequestParam(value = "moduleId") Long moduleId,
                             Page page,
                             HttpServletRequest request){
        
        ModelAndView modelAndView = new ModelAndView("content/article/article-module-list");
        
        List<ArticleModule> articles = articleService.list(moduleId, page);
        
        modelAndView.addObject("articles", articles);
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "list");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * Display search panel
     * 
     * @return
     */
    @RequestMapping(value="/search", method=RequestMethod.GET)
    public String search(){
        return "content/article/article-search";
    }
    
    /**
     * @param articleModuleSearch
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = {"filter", "moduleId"})
    @MenuSetting("submenu-article-management")
    public ModelAndView onSearch(ArticleModuleSearch articleModuleSearch,
                                 HttpServletRequest request, 
                                 Page page){
        
        ModelAndView modelAndView = new ModelAndView("content/article/article-module-list");
        
        List<ArticleModule> articles = articleService.search(articleModuleSearch, page);
        
        modelAndView.addObject("articles", articles);
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "search");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
        
        return modelAndView;
    }

    /**
     * 
     * @param articleSearch
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-article-management")
    public ModelAndView onSearch(ArticleSearch articleSearch,
                                 HttpServletRequest request, 
                                 Page page){
        
        ModelAndView modelAndView = new ModelAndView("content/article/article-list");
            
        List<Article> articles = articleService.search(articleSearch, page);
        
        modelAndView.addObject("articles", articles);
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "search");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
        
        return modelAndView;
    }

    
    /**
     * Display create panel
     * 
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    @MenuSetting("submenu-article-management")
    public String create(){
        return "content/article/article-create";
    }
    
    /**
     * @param article
     * @param moduleIds
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody String onCreate(Article article,
                                         @RequestParam("moduleIds") List<Long> moduleIds){
        
        Result result = new Result();
        
        try{
            
            articleService.createArticle(article, moduleIds);
            
            result.success().message("创建文章成功");
        
        }catch(Exception e){
            
            logger.error("ArticleController#onCreate() error:", e);
            
            result.fail().message("创建文章失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * Display delete panel
     * 
     * @param articleId
     * @return
     */
    @RequestMapping(value = "/{articleId}/delete", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable("articleId") Long articleId){
        
        ModelAndView modelAndView = new ModelAndView("content/article/article-delete");
        
        modelAndView.addObject("articleId", articleId);
        
        return modelAndView;
    }
    
    /**
     * Do delete article
     * 
     * @param articleId
     * @return
     */
    @RequestMapping(value="/{articleId}", method=RequestMethod.DELETE)
    public @ResponseBody String onDelete(@PathVariable("articleId") Long articleId){
        
        Result result = new Result();
        
        try{
            
            Article article = articleService.load(Article.class, articleId);
            
            articleService.disable(article);
            
            result.success().message("删除文章成功");
        
        }catch(Exception e){
            
            logger.error("ArticleController#onDelete() error:", e);
            
            result.fail().message("删除文章失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * Display stick article panel
     * 
     * @param articleId
     * @param moduleId
     * @return
     */
    @RequestMapping(value="/{articleId}/stick", method=RequestMethod.GET)
    public ModelAndView stick(@PathVariable("articleId") Long articleId, @RequestParam("moduleId") Long moduleId){
        
        ModelAndView modelAndView = new ModelAndView("content/article/article-stick");
        
        modelAndView.addObject("articleId", articleId);
        modelAndView.addObject("moduleId", moduleId);
        
        return modelAndView;
    }

    /**
     * Do stick article
     * 
     * @param articleId
     * @param moduleId
     * @return
     */
    @RequestMapping(value="/{articleId}/stick", method=RequestMethod.PATCH)
    public @ResponseBody String onStick(@PathVariable("articleId") Long articleId, @RequestParam("moduleId") Long moduleId){
        
        Result result = new Result();
        
        try {
               
            Article article = articleService.load(Article.class, articleId);
            Module module = moduleService.load(Module.class, moduleId); 
            
            articleService.stick(article, module);
            
            result.success().message("置顶文章成功");
           
        } catch (Exception e) {
           
            logger.error("ActivityController#onStick() error:", e);
           
            result.fail().message("置顶文章失败!");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * Display unstick article panel
     * 
     * @param articleId
     * @param moduleId
     * @return
     */
    @RequestMapping(value="/{articleId}/unstick", method=RequestMethod.GET)
    public ModelAndView unstick(@PathVariable("articleId") Long articleId, @RequestParam("moduleId") Long moduleId){
        
        ModelAndView modelAndView = new ModelAndView("content/article/article-unstick");
        
        modelAndView.addObject("articleId", articleId);
        modelAndView.addObject("moduleId", moduleId);
        
        return modelAndView;
    }
    
    /**
     * Do unstick article
     * 
     * @param articleId
     * @param moduleId
     * @return
     */
    @RequestMapping(value="/{articleId}/unstick", method=RequestMethod.PATCH)
    public @ResponseBody String onUnstick(@PathVariable("articleId") Long articleId, @RequestParam("moduleId") Long moduleId){
        
        Result result = new Result();
        
        try {
            
            Article article = articleService.load(Article.class, articleId);
            Module module = moduleService.load(Module.class, moduleId); 
            
            articleService.unstick(article, module);
            
            result.success().message("取消置顶文章成功");
           
        } catch (Exception e) {
           
            logger.error("ActivityController#onUnstick() error:", e);
           
            result.fail().message("取消置顶文章失败!");
        }
        
        return JsonUtils.toJsonString(result);
    }

    /**
     * Display article view panel
     * 
     * @param articleId
     * @return
     */
    @RequestMapping(value="/{articleId}", method=RequestMethod.GET)
    @MenuSetting("submenu-article-management")
    public ModelAndView view(@PathVariable("articleId") Long articleId){

        ModelAndView modelAndView = new ModelAndView("content/article/article-view");
        
        Article article = articleService.load(Article.class, articleId);
        
        modelAndView.addObject("article", article);
        
        return modelAndView;
    }
    
    /**
     * Display edit panel
     * 
     * @param articleId
     * @return
     */
    @RequestMapping(value = "/{articleId}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("articleId") Long articleId){
        
        ModelAndView modelAndView = new ModelAndView("content/article/article-edit");
        
        Article article = articleService.load(Article.class, articleId);
        
        modelAndView.addObject("article", article);
        
        return modelAndView;
    }

    /**
     * @param article
     * @param moduleIds
     * @return
     */
    @RequestMapping(value = "/{articleId}", method = RequestMethod.PATCH)
    public @ResponseBody String onEdit(@Preloading("articleId") Article article,
                                       @RequestParam("moduleIds") List<Long> moduleIds){
        
        Result result = new Result();
        
        try {
            
            articleService.editArticle(article, moduleIds);
            
            result.success().message("修改文章成功");
            
        } catch(Exception e){
            
            logger.error("ArticleController#onEdit() error:", e);
            
            result.fail().message("修改文章失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * Display edit cover panel
     * 
     * @param articleId
     * @return
     */
    @RequestMapping(value = "/{articleId}/cover", method = RequestMethod.GET)
    public ModelAndView editCover(@PathVariable("articleId") Long articleId){
        
        ModelAndView modelAndView = new ModelAndView("content/article/article-cover-edit");
        
        Article article = articleService.load(Article.class, articleId);
        
        modelAndView.addObject("article", article);
        
        return modelAndView;
    }
    
    /**
     * Do edit cover
     * 
     * @param articleId
     * @param cover
     * @return
     */
    @RequestMapping(value = "/{articleId}/cover", method = RequestMethod.PATCH)
    public @ResponseBody String onEditCover(@PathVariable("articleId") Long articleId, String cover){
        
        Result result = new Result();
        
        try {
            
            Article article = articleService.load(Article.class, articleId);
            
            articleService.update(article.editCover(cover));
            
            result.success().message("修改文章封面成功");
            
        }catch(Exception e){
            
            logger.error("ArticleController#onEdit() error:", e);
            
            result.fail().message("修改文章封面失败");
        }
   
        return JsonUtils.toJsonString(result);
    }

}
